#ifndef _MACHINE_H_
#define _MACHINE_H_

#include <iostream>
#include <unordered_map>
#include <memory>
#include "../Event.h"
#include "../Action.h"
#include "../State.h"
#include "../Context.h"

typedef std::unordered_map<int, std::shared_ptr<Action>> EventAction;

class Machine{
public:
    virtual void Init() = 0;

    std::shared_ptr<State> Execute(int state, std::shared_ptr<Event> event, std::shared_ptr<Context> context = NULL)
    {
        if(m_stateEventsMap.count(state) == 0)
        {
            std::cout << "状态未注册" << std::endl; 
            return NULL;
        }
    
        EventAction ea = m_stateEventsMap[state]; 
    
        if(ea.count(event->m_eventId) == 0) 
        {
            std::cout << "未注册事件" << std::endl;
            return NULL;
        }
    
        std::shared_ptr<State> curState = std::make_shared<UserState>(state);
    
        return ea[event->m_eventId]->Execute(curState, event, context);
    }

    std::shared_ptr<State> Execute(std::shared_ptr<State> state, std::shared_ptr<Event> event, std::shared_ptr<Context> context = NULL)
    {
        if(m_stateEventsMap.count(state->m_stateId) == 0)
        {
            std::cout << "状态未注册" << std::endl; 
            return NULL;
        }

        EventAction ea = m_stateEventsMap[state->m_stateId];

        if(ea.count(event->m_eventId) == 0) 
        {
            std::cout << "未注册事件" << std::endl;
            return NULL;
        }

        return ea[event->m_eventId]->Execute(state, event, context);
    }
public:
    std::unordered_map<int, std::unordered_map<int, std::shared_ptr<Action>>> m_stateEventsMap;        // <状态id,<事件id, Action>> 
};

#endif